﻿using Cemit.NetFramework.Logger;
using Cemit.PolyProto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cemit.NetFramework
{
    partial class PolyNetwork
    {
        private static readonly LobbyClient lobbyClient = new LobbyClient();
        
        /// <summary>加入到大厅</summary>
        public static async Task<AsyncReport> JoinLobby(LobbyInfo lobbyInfo, string name)
        {
            playerName = name;

            Debug.LogInfo($"尝试连接至大厅服务器：{lobbyInfo.Name}");

            //连接到大厅服务器
            var connectReport = await lobbyClient.Connect(lobbyInfo.Ip, lobbyInfo.Port);

            //连接大厅服务器失败
            if (!connectReport.isSucceed)
            {
                return new AsyncReport(false, $"连接到大厅服务器失败，{connectReport.output}");
            }

            Debug.LogInfo($"已连接至大厅服务器，正在尝试使用 \"{name}\" 加入进大厅。");

            //登录到大厅
            LoginResult loginResult = await lobbyClient.Login(playerName);

            //登录失败
            if (loginResult != LoginResult.Successful)
            {
                return new AsyncReport(false, $"登录到大厅失败：{loginResult}");
            }

            Debug.LogInfo($"加入大厅成功。");

            return new AsyncReport(true);
        }

        /// <summary>加入匹配</summary>
        public static bool JoinMatch(Action<MatchInfo> onMatchComplete, short peopleNumber)
        {
            if (!lobbyClient.IsConnected)
            {
                Debug.LogError("加入匹配失败：服务器已断开！");
                return false;
            }

            Debug.LogInfo($"开始加入匹配。");
            lobbyClient.JoinMatch(matchInfo => MonoHandle.Invoke(onMatchComplete, matchInfo), peopleNumber);
            return true;
        }

        /// <summary>确认匹配，取得匹配结果</summary>
        public async static Task<(MatchResult matchResult, GameRoomInfo roomInfo)> ConfirmMatch(MatchInfo matchInfo)
        {
            Debug.LogInfo($"已确认匹配。");

            var result = await lobbyClient.ConfirmMatch(matchInfo);

            if (result.matchResult != MatchResult.Successful)
            {
                Debug.LogWarning($"匹配失败：{result.matchResult}");
                return result;
            }
            
            Debug.LogInfo("匹配已成功！");

            return result;
        }
    }

    public class MatchInfo
    {

    }
}
